package br.ufpe.cin.mouse.pizza.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import br.ufpe.cin.mouse.pizza.Status;
import br.ufpe.cin.mouse.pizza.Util;
import br.ufpe.cin.mouse.pizza.model.Order;
import br.ufpe.cin.mouse.pizza.pojo.ItemPedido;
import br.ufpe.cin.mouse.pizza.pojo.Pedido;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

/**
 * This servlet responds to the request corresponding to cardapio.
 * 
 * @author
 */
@SuppressWarnings("serial")
public class PainelServlet extends BaseServlet {

	private static final Logger logger = Logger.getLogger(OrderServlet.class
			.getCanonicalName());
	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = req.getParameter("action");
		if (action.equalsIgnoreCase("delete")) {
			doDelete(req, resp);
			return;
		} else if (action.equalsIgnoreCase("put")) {
			doPut(req, resp);
			return;
		}
	}

	protected void doPut(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		logger.log(Level.INFO, "Inserting order into listing");

		String orderID = req.getParameter("txtorderid");

		// Atualiza dados do cliente
		Order.atualizarStatus(orderID);

	}

	/**
	 * Get the requested orders and the line items in JSON format
	 */
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		super.doGet(req, resp);
		logger.log(Level.INFO, "Getting pedidos from listing");

		// listagem dos pedidos

		Iterable<Entity> entities = null;
		PrintWriter out = resp.getWriter();
		//entities = Order.getAllOrders();
		entities = Util.listEntities("Order", "status", Status.RECEBIDO.toString());
		out.println(Util.writeJSONPainel(prepararPedidos(entities)));

	}

	private ArrayList<Pedido> prepararPedidos(Iterable<Entity> entities) {

		ArrayList<Pedido> pedidos = new ArrayList<Pedido>();
		
		SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy hh:mm");
		formatador.setTimeZone(TimeZone.getTimeZone("GMT-3"));
		
		for (Entity result : entities) {

			Pedido pedido = new Pedido();
			
			pedido.setName(""+result.getKey().getId());
			pedido.setCustomerName((String)result.getProperty("customerName"));
			Date data = (Date)result.getProperty("data");
			pedido.setData(formatador.format(data.getTime()));
			pedido.setStatus((String)result.getProperty("status"));
			
			Iterable<Entity> entities1 = Order.getLineItens(result.getKey()
					.getId());
			
			ArrayList<ItemPedido> itens = new ArrayList<ItemPedido>();
			
			double vlTotal = 0;
			
			for (Entity resultItens : entities1) {

				ItemPedido resultItem = new ItemPedido();

				resultItem.setItemName((String)resultItens.getProperty("itemName"));
				resultItem.setProduct((String)resultItens.getProperty("product"));
				resultItem.setQuantity((String)resultItens.getProperty("quantity"));
				resultItem.setPrice((String)resultItens.getProperty("price"));				
				resultItem.setTotal((String)resultItens.getProperty("total"));
				
				vlTotal += Util.trocaVirgulaPonto((String)resultItens.getProperty("total"));

				itens.add(resultItem);
			}
			
			pedido.setItens(itens);
			pedido.setTotal(Util.trocaPontoVirgula(vlTotal));
			pedidos.add(pedido);
		}

		return pedidos;
	}
}
